from sqlalchemy import *
import log
import os,sys


log.logger.info("creating db connection...")
error_try = 0
while True:
	try:
		import MySQLdb
		my_sql_connection = MySQLdb.connect(host="localhost", port=3038,
				user="root", passwd="", db="qres" )
		my_cursor = my_sql_connection.cursor()
		break
	except MySQLdb.Error, e:
		log.logger.error(e.args)
		error_try += 1
		if error_try > 4:
			log.logger.critical('System database errors exceed maximum errors:%d' % error_try)
			sys.exit(sys.EX_IOERR)			
		if e.args[0]==2003:
			log.logger.warn("no databases server found(%d)" % error_try)
			log.logger.info("starting server")
			os.system('start_mysql_server.bat')
		if e.args[0]==1049:
			log.logger.warn("database server already up but there is no database(%d)" % error_try)
			log.logger.info("importing default core.sql")
			import os
			os.system(r'c:\qresmysql\bin\mysql.exe -P3038 < c:\qresmysql\core.sql')

db = create_engine('mysql://root@localhost:3038/qres')
metadata = BoundMetaData(db)
metadata.engine.echo = False

session = create_session()
log.logger.debug('db and session created successfully')
